package com.example.gokuplayalong.bases.tools;

import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.util.Log;

import com.example.gokuplayalong.bases.beans.AppParams;
import com.kongzue.dialogx.dialogs.TipDialog;
import com.kongzue.dialogx.dialogs.WaitDialog;

import java.io.File;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Random;
import java.util.UUID;

public class Tools {
    @SuppressLint("SimpleDateFormat")
    public static SimpleDateFormat getSDF() {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    }

    @SuppressLint("SimpleDateFormat")
    public static SimpleDateFormat getSDFSimple() {
        return new SimpleDateFormat("MM-dd HH:mm");
    }

    public static SimpleDateFormat getSDFSimpleYMD() {
        return new SimpleDateFormat("yyyy-MM-dd");
    }

    public static SimpleDateFormat getSDFSimpleHMS() {
        return new SimpleDateFormat("HH小时mm分钟ss秒");
    }

    public static double doubleFormat(double d) {
        DecimalFormat df = new DecimalFormat("#.##");
        return Double.parseDouble(df.format(d));
    }

    public static void copyTextToClipboard(Context context, String text) {
        ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        if (clipboard != null) {
            clipboard.setPrimaryClip(ClipData.newPlainText("label", text));
        }
    }

    public static String getTimsFormat(long times) {
        //获取小时
        int h, m, s;
        h = (int) (times / 3600.0f);
        m = (int) ((times % 3600.0f) / 60.0f);
        s = (int) (((times % 3600.0f) % 60.0f));
        if (h == 0) {
            if (m == 0)
                return s + "秒";
            else
                return m + "分钟" + s + "秒";
        }
        else {
            return h + "小时" + m + "分钟" + s + "秒";
        }
    }

    public static String getOrderNum() {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault());
        Date date = new Date();
        String key = format.format(date);

        return key;
    }

    public static String getTimes() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        Date date = new Date();

        return format.format(date);
    }

    public static boolean Deshak() {
        if (System.currentTimeMillis() - AppParams.getInstance().deshakLast > 500) {
            AppParams.getInstance().deshakLast = System.currentTimeMillis();
            return true;
        }
        else {
//            Logger.d("deshak", "" + (System.currentTimeMillis() - AppParams.getInstance().deshakLast));
            return false;
        }
    }

    public static boolean Deshak(int time) {
        if (System.currentTimeMillis() - AppParams.getInstance().deshakLast > time) {
            //  Logger.d("deshak",""+(System.currentTimeMillis() - AppParams.getInstance().deshakLast));
            AppParams.getInstance().deshakLast = System.currentTimeMillis();
            return true;
        }
        else {
            // AppParams.getInstance().deshakLast = System.currentTimeMillis();
            return false;
        }
    }


    public static String getRandomNickname(int length) {
        String val = "";
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            val += String.valueOf(random.nextInt(10));
        }
        return val;
    }

    public static String getInitRandomUserId(String head, int length) {
        String val = "";
        val += head;
        Random random = new Random();
        for (int i = 0; i < length - 1; i++) {
            val += String.valueOf(random.nextInt(10));
        }
        return val;
    }

    /**
     * 获取精确到秒的时间戳
     */
    public static String getTimeStamp() {
        return String.valueOf(System.currentTimeMillis() / 1000);
    }

    public static String[] addStringToArray(String[] in, String newStr) {
        String[] temp = new String[in.length + 1];
        for (int i = 0; i < in.length; i++) {
            temp[i] = in[i];
        }
        temp[in.length] = newStr;
        return temp;
    }

    public static String getUUID() {
        String serial = "SN";
        String m_szDevIDShort = "随机两位数" +
                Build.BOARD.length() % 10 + Build.BRAND.length() % 10 +
                Build.CPU_ABI.length() % 10 + Build.DEVICE.length() % 10 +
                Build.DISPLAY.length() % 10 + Build.HOST.length() % 10 +
                Build.ID.length() % 10 + Build.MANUFACTURER.length() % 10 +
                Build.MODEL.length() % 10 + Build.PRODUCT.length() % 10 +
                Build.TAGS.length() % 10 + Build.TYPE.length() % 10 +
                Build.USER.length() % 10; //13 位
        //使用硬件信息拼凑出来的15位号码
        return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()) + "-" + Build.BRAND + "-" + Build.MODEL;
    }

    public static String getApkVersionName(Context context, String apkPath) {
        PackageManager pm = context.getPackageManager();
        PackageInfo info = pm.getPackageArchiveInfo(apkPath, PackageManager.GET_ACTIVITIES);
        if (info != null) {
            ApplicationInfo appInfo = info.applicationInfo;
            String packageName = appInfo.packageName;  //得到安装包名称
            String version = info.versionName;//获取安装包的版本号
            try {
                return version;
            } catch (OutOfMemoryError e) {
                Log.i("mylog", "GetApkInfo: " + e);
            }
        }
        return null;
    }

    public static String hidePhone(String phone) {
        return phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
    }

    public static String hideEmail(String email) {
        return email.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
    }

    public static void disconnect(Context context) {
        TipDialog.show("网络连接失败!", WaitDialog.TYPE.WARNING);
    }

    public static void deleteDirWihtFile(File dir) {
        if (dir == null || !dir.exists() || !dir.isDirectory())
            return;
        for (File file : dir.listFiles()) {
            if (file.isFile())
                file.delete();
            else if (file.isDirectory())
                deleteDirWihtFile(file);
        }
//        dir.delete();
    }

    /**
     * 获取当前程序行数，类名，方法名
     *
     * @return 行数，类名，方法名
     */
    public static String getTraceInfo() {
        StringBuffer sb = new StringBuffer();
        StackTraceElement[] stacks = new Throwable().getStackTrace();
        int stacksLen = stacks.length;
        sb.append("; number: ").append(stacks[1].getLineNumber())
                .append("class: ").append(stacks[1].getClassName())
                .append("; method: ").append(stacks[1].getMethodName());
        return sb.toString();
    }

    public static String getIPAddress(Context context) {
        NetworkInfo info = ((ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
        if (info != null && info.isConnected()) {
            if (info.getType() == ConnectivityManager.TYPE_MOBILE) {//当前使用2G/3G/4G网络
                try {
                    //Enumeration<NetworkInterface> en=NetworkInterface.getNetworkInterfaces();
                    for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                        NetworkInterface intf = en.nextElement();
                        for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                            InetAddress inetAddress = enumIpAddr.nextElement();
                            if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                                return inetAddress.getHostAddress();
                            }
                        }
                    }
                } catch (SocketException e) {
                    e.printStackTrace();
                }

            }
            else if (info.getType() == ConnectivityManager.TYPE_WIFI) {//当前使用无线网络
                WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                String ipAddress = intIP2StringIP(wifiInfo.getIpAddress());//得到IPV4地址
                return ipAddress;
            }
        }
        else {
            //当前无网络连接,请在设置中打开网络
        }
        return null;
    }

    /**
     * 将得到的int类型的IP转换为String类型
     *
     * @param ip
     * @return
     */
    public static String intIP2StringIP(int ip) {
        return (ip & 0xFF) + "." +
                ((ip >> 8) & 0xFF) + "." +
                ((ip >> 16) & 0xFF) + "." +
                (ip >> 24 & 0xFF);
    }
}
